package org.joor.harmony.toast;

import org.joor.Reflect;

import java.lang.reflect.InvocationTargetException;

/**
 * Android Toast
 */
public class Toast {
    /**
     * 短Toast
     */
    public static final int LENGTH_SHORT = 0;
    /**
     * 长Toast
     */
    public static final int LENGTH_LONG = 1;

    /**
     * Android的ApplicationContext
     */
    private final Object context;
    /**
     * Toast内容
     */
    private final CharSequence text;
    /**
     * 显示时长
     */
    private final int duration;

    private Toast(Object context, CharSequence text, int duration) {
        this.context = context;
        this.text = text;
        this.duration = duration;
    }

    /**
     * 创建一个Toast实例
     *
     * @param text     Toast内容
     * @param duration 时长
     * @return Toast实例
     */
    public static Toast makeText(CharSequence text, int duration) {
        return new Toast(getApplicationByReflect(), text, duration);
    }

    /**
     * 显示Toast
     */
    public void show() {
        Reflect.on("android.widget.Toast")
                .call("makeText", context, text, duration)
                .call("show");
    }

    /**
     * 反射ActivityThread获取Context
     */
    private static Object getApplicationByReflect() {
        try {
            Class<?> activityThread = Class.forName("android.app.ActivityThread");
            Object thread = activityThread.getMethod("currentActivityThread").invoke(null);
            Object app = activityThread.getMethod("getApplication").invoke(thread);
            if (app == null) {
                throw new NullPointerException("u should init first");
            }
            return app;
        } catch (NoSuchMethodException | IllegalAccessException
                | InvocationTargetException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        throw new NullPointerException("u should init first");
    }
}